import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

type RequestOptions = {
  url: string
  params?: any
  data?: any
  headers?: Record<string, string>
}

// 简易响应体统一处理（后端常见格式：{ code, data, msg }）
function unwrapResponse<T = any>(resp: AxiosResponse<T>): T {
  const r: any = resp.data
  if (r && typeof r === 'object' && 'code' in r && 'data' in r) {
    if (r.code === 0) return r.data
    throw new Error(r.msg || '请求错误')
  }
  return resp.data as T
}

const baseURL = import.meta.env.VITE_API_URL as string

const instance: AxiosInstance = axios.create({
  baseURL,
  timeout: 15000
})

instance.interceptors.request.use((config) => {
  const token = localStorage.getItem('accessToken')
  const tenantId = localStorage.getItem('tenant-id') || (import.meta.env.VITE_TENANT_ID as string) || ''
  config.headers = config.headers || {}
  if (token) {
    ;(config.headers as any)['Authorization'] = `Bearer ${token}`
  }
  if (tenantId) {
    ;(config.headers as any)['tenant-id'] = tenantId
  }
  ;(config.headers as any)['terminal'] = 'pc'
  ;(config.headers as any)['Accept'] = '*/*'
  return config
})

instance.interceptors.response.use(
  (resp) => resp,
  (error) => {
    const msg = error?.response?.data?.msg || error.message || '网络错误'
    return Promise.reject(new Error(msg))
  }
)

const request = {
  get<T = any>({ url, params, headers }: RequestOptions) {
    const cfg: AxiosRequestConfig = { url, method: 'GET', params, headers }
    return instance.request<T>(cfg).then(unwrapResponse)
  },
  post<T = any>({ url, data, headers }: RequestOptions) {
    const cfg: AxiosRequestConfig = { url, method: 'POST', data, headers }
    return instance.request<T>(cfg).then(unwrapResponse)
  },
  put<T = any>({ url, data, headers }: RequestOptions) {
    const cfg: AxiosRequestConfig = { url, method: 'PUT', data, headers }
    return instance.request<T>(cfg).then(unwrapResponse)
  },
  delete<T = any>({ url, params, headers }: RequestOptions) {
    const cfg: AxiosRequestConfig = { url, method: 'DELETE', params, headers }
    return instance.request<T>(cfg).then(unwrapResponse)
  },
  download({ url, params }: RequestOptions) {
    const cfg: AxiosRequestConfig = { url, method: 'GET', params, responseType: 'blob' }
    return instance.request(cfg)
  }
}

export default request